package org.singledog.permission.config;

import org.singledog.permission.core.PermissionApplicationContext;
import org.singledog.permission.core.PermissionSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * Permission核心配置
 *
 * @author liuzheming
 * @since 2021.9.14
 */
@Configuration
@EnableConfigurationProperties(PermissionProperties.class)
@ConditionalOnClass({PermissionApplicationContext.class, PermissionSource.class})
public class PermissionAutoConfiguration {

    private PermissionProperties permissionProperties;

    /**
     * 获取PermissionProperties配置
     *
     * @param permissionProperties {@link PermissionProperties}
     */
    public PermissionAutoConfiguration(PermissionProperties permissionProperties) {
        this.permissionProperties = permissionProperties;
    }

    /**
     * 初始化PermissionApplicationContext，对应的类{@link PermissionApplicationContext}
     */
    @Bean
    public PermissionApplicationContext initPermissionApplicationContext() {
        String[] factory = permissionProperties.getFactory();
        PermissionApplicationContext applicationContext = new PermissionApplicationContext();
        if (factory != null && factory.length > 0) {
            Arrays.stream(factory).forEach(a -> applicationContext.addPermission(a));
        }
        return applicationContext;
    }

}

